package com.woniuxy.pxxt.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: redis 配置类
 * <P> Date: 2022/2/28:18:39
 * <P> Description:
 */
@Component
@EnableCaching //开启缓存
public class RedisConfigTemplate extends CachingConfigurerSupport {
    /**
     * TODO: redisTemplate配置 这个是直接可以调用redis方法来执行业务
     **/
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.json());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        return redisTemplate;
    }

    /**
        * TODO:配置SpringCache整合redis的配置 SpringCache是Spring自带的缓存模块，内部提供了很多缓存接口，
     *      * 这里用的是redis来实现的缓存！ 注解缓存使用的！
    **/
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        //使用默认缓存配置
        //配置序列化方案
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return redisCacheConfiguration;
    }
}
